package fzw.jsmx.androidapt;

import android.app.Activity;

import androidx.lifecycle.ViewModel;

import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.disposables.Disposable;

public abstract class BaseViewModel extends ViewModel {

    private Disposable subscribe;
    private final String[] permission;
    protected boolean isCheck = false;

    public BaseViewModel(String[] permission) {
        this.permission = permission;
    }

    /**
     * 初始化不需要权限的数据
     */
    protected abstract void initialize();

    /**
     * 初始化UI
     */
    protected abstract void initUI();

    /**
     * 添加监听
     */
    protected abstract void setListener();

    /**
     * 没有获得足够的权限
     */
    protected abstract void noPermission();

    public void resume() {

    }

    public void pause() {

    }

    public void checkPermission(Activity activity) {
        subscribe = new RxPermissions(activity)
                .request(permission)
                .subscribe(b -> {
                    isCheck = b;
                    if (b) {
                        initUI();
                        setListener();
                    } else {
                        noPermission();
                    }
                });
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (null != subscribe && subscribe.isDisposed()) {
            subscribe.dispose();
            subscribe = null;
        }
    }
}
